package com.tongtong.middleware.blockchain.controller;

import cn.hutool.json.JSONUtil;
import com.tongtong.middleware.blockchain.client.bsn.BSNService;
import com.tongtong.middleware.vo.params.bsn.RechargeRequest;
import com.tongtong.middleware.vo.response.bsn.PowerBalanceRes;
import com.tongtong.middleware.vo.response.bsn.RechargeRes;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.xtt.common.response.ApiResult;

import java.util.Objects;

@RestController
@RequestMapping("/bsn")
@Slf4j
public class BSNController {
    @Autowired
    BSNService bsnService;
    /**
     * 能量值充值
     */
    @PostMapping("/gas/recharge")
    public ApiResult<String> recharge(@Valid @RequestBody RechargeRequest request, BindingResult bindingResult) {
        log.info("【成功】/bsn/gas/recharge request:  hashRateValue=>{} opbChainClientAddress=>{} opbChainId=>{}",
                request.getHashRateValue(), request.getOpbChainClientAddress(), request.getOpbChainId());
        if (bindingResult.hasErrors()) {
            return ApiResult.failure(9527, Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        RechargeRes res = bsnService.recharge(request);
        log.info("【成功】/bsn/gas/recharge response: {}", JSONUtil.toJsonStr(res));
        if (res.getErrorLogCode() == null) {
            return ApiResult.ok(res.getData().getEnergyValue());
        } else {
            log.error("【失败】/bsn/gas/recharge response: {}", res.getErrorLogMessage());
            return ApiResult.failure(1, res.getErrorLogMessage());
        }
    }
    /**
     * 算力余额查询
     */
    @PostMapping("/gas/balance")
    public ApiResult<Double> balance() {
        PowerBalanceRes res = bsnService.getPowerBalance();
        log.info("/bsn/gas/balance response: {}", JSONUtil.toJsonStr(res));
        if (res.getErrorLogCode() == null) {
            return ApiResult.ok(res.getData().getAccountBalance());
        } else {
            return ApiResult.failure(1, res.getErrorLogMessage());
        }
    }
}
